package com.example.home.viewmodel

import android.util.Log
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.example.base.bean.ResponseResult
import com.example.base.base.mvi.setState
import com.example.base.base.viewmodel.BaseVBViewModel
import com.example.base.base.viewmodel.BaseViewModel
import com.example.home.bean.request.Location
import com.example.home.bean.request.MarkerCardRequest
import com.example.home.repository.HomeRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext

/**
 * @Description
 * @department 城市元宇宙组
 * @Author niushilong
 * @Date 2024-04-05 17:29
 */
class HomeViewModel(
    private val repository: HomeRepository = HomeRepository()
): BaseVBViewModel<HomeIntent, HomeState, HomeEffect>() {
    companion object{
        private const val TAG = "HomeViewModel"
    }
    override fun initUiState(): HomeState{
        return HomeState(MarkerUiState.INIT, MarkerCardState.INIT, LoadUiState.Idle)
    }

    override fun handleIntent(intent: HomeIntent) {
        when (intent){
            is HomeIntent.RequestMarkerList -> requestMarkerList(intent.location)
            is HomeIntent.RequestMarkerInfo -> requestMarkerCardList(intent.request)
        }
    }

    fun navigationToMyPage(userId: String){
        sendEffect{
            HomeEffect.NavigationMyPage(userId)
        }
    }

    private fun requestMarkerList(location: Location){
        Log.v(TAG, "请求Marker数据")
        launchOnUI {
            // 开始加载
            updateUiState {
                copy(loadUiState = LoadUiState.Loading(true))
            }

            val result = repository.getMarkerList(location)
            result.checkResult(success = {markers ->
                updateUiState {
                    copy(markerUiState = MarkerUiState.SUCCESS(markers ?: emptyList())
                    , loadUiState = LoadUiState.ShowContent)
                }
            }, error = { errMsg ->
                // 请求失败
                updateUiState {
                    copy(loadUiState = LoadUiState.Error(errMsg ?: "未知错误"))
                }
            })
        }
    }

    private fun requestMarkerCardList(request: MarkerCardRequest){
        launchOnUI {
            updateUiState {
                copy(loadUiState = LoadUiState.Loading(true))
            }

            val result = repository.getMarkerCardList(request)

            result.checkResult(success = {
                updateUiState {
                    copy(markerCardState = MarkerCardState.SUCCESS(it ?: emptyList())
                    , loadUiState = LoadUiState.ShowContent)
                }
            }, error = {
                updateUiState {
                    copy(loadUiState = LoadUiState.Error(it ?: "未知错误"))
                }
            })
        }
    }

}